package com.longcheer.weibo;

import java.util.Map;

import android.content.Context;

import com.longcheer.weibo.vo.Province;
import com.longcheer.weibo.vo.User;
import com.weibo.net.WeiboException;

public class ProvinceManager {
    
    private Map<Integer, Province> provinceMap;
    
    private static ProvinceManager instance;
    
    private ProvinceManager(Context context) {
        provinceMap = WeiboProvider.getProvinces(context);
    }
    
    public static ProvinceManager getInstance(Context context) {
        if (instance == null) {
            instance  = new ProvinceManager(context);
        }
        
        return instance;
    }
    
    public String getUserProvinceString(Context context, User user) {
        
        StringBuilder info = new StringBuilder();
        
        try {
            check(context);
        } catch (WeiboException e) {
            e.printStackTrace();
            return info.toString();
        }
        
        Province province = provinceMap.get(user.getProvince());
        if (province != null) {
            info.append(province.getName());
            String cityName = province.getCityMap().get(user.getCity());
            if (cityName != null) {
                info.append(" ").append(cityName);
            }
        }
        
        return info.toString();
    }
    
    private void check(Context context) throws WeiboException {
        if (provinceMap == null || provinceMap.size() == 0) {
            provinceMap = WeiboProvider.getProvinces(context);
            if (provinceMap.size() == 0) {
                provinceMap = WeiboHelper.getInstance().getProvinces(context);
                WeiboProvider.saveProvinces(context, provinceMap);
            }
        }
    }
}
